const express = require('express')
const path = require('path')
const formidable = require('formidable')
const decodeImage = require('jimp').read // 解析二维码图片
const qrcodeReader = require('qrcode-reader')// 解析二维码类容
var qr = require('qr-image')//生成二维码
// 上传文件集合
const uploadFile = require(path.join(__dirname, '../models/music_db/upload_file.js'))
// 客户端用户集合
const userManage = require(path.join(__dirname, '../models/music_db/user_manage.js'))
// 用户等级集合
const vipManage = require(path.join(__dirname, '../models/music_db/vip_grade.js'))
//  用户评论集合
const commentManage = require(path.join(__dirname, '../models/music_db/comment.js'))
const util = require('../utils/index')

const router = express.Router()
const SUCCESS = '00000'
const ERROR = '99998'
function handData(value) {
  return JSON.parse(JSON.stringify(value))
}

// 文件上传(现在是包括图片等文件)
router.post('/common/upload', (request, response, next) => {
  const form = new formidable.IncomingForm({
    keepExtensions: true,
    uploadDir: path.join(__dirname, '../upload/files'),
    filter: function (file) {
      return true
    }
  })
  //解析客户端传递过来的formData对象
  form.parse(request, (err, fields, { file }) => {
    //req:请求对象，err错误对象，filelds：普通请求参数的内容
    //files：文件的内容的参数包括保存的地址信息
    if (err) {
      next(['上传失败', ERROR])
    } else {
      const params = {
        fileName: file.originalFilename,
        filePath: '/' + /(upload\\files).+$/.exec(file.filepath)[0].split('\\').join('/'),
        uploadTime: file.lastModifiedDate,
        ext: file.filepath.split('.')[1]
      }
      const upload_file = new uploadFile(params)
      upload_file.save().then(
        () => {
          response.json({
            code: SUCCESS,
            data: params
          })
        },
        () => {
          next()
        }
      )
    }
  })
})

// 歌曲上传
router.post('/manage/upload', (request, response, next) => {
  const form = new formidable.IncomingForm({
    keepExtensions: true,
    uploadDir: path.join(__dirname, '../upload/songs'),
    filter: function (file) {
      return true
    }
  })
  //解析客户端传递过来的formData对象
  form.parse(request, (err, fields, { file }) => {
    //req:请求对象，err错误对象，filelds：普通请求参数的内容
    //files：文件的内容的参数包括保存的地址信息
    if (err) {
      next(['上传失败', ERROR])
    } else {
      const params = {
        fileName: file.originalFilename,
        filePath: '/' + /(upload\\songs).+$/.exec(file.filepath)[0].split('\\').join('/'),
        uploadTime: file.lastModifiedDate,
        ext: file.filepath.split('.')[1]
      }
      const upload_file = new uploadFile(params)
      upload_file.save().then(
        () => {
          response.json({
            code: SUCCESS,
            data: params
          })
        },
        () => {
          next()
        }
      )
    }
  })
})

/* 公共接口 */

// 新增用户
router.post('/common/user-register', async (request, response, next) => {
  // 参数
  let { userPhone, password } = request.body
  // 电话验证
  if (!util.phone(userPhone)) return next(['电话号格式不正确', ERROR])
  // 密码验证
  // if (!util.password(password)) return next(['密码是6-18位的数字和字符', ERROR]) 传过来的是一个MD5，所以不验证
  // 查询是否注册
  await userManage.findOne({ account: userPhone }).then(value => {
    if (value) {
      next(['电话号已经被注册', ERROR])
      return Promise.reject('电话号已经被注册')
    } else {
      return Promise.resolve()
    }
  })
  // 新增
  const usermanage = new userManage({
    userPhone, // 电话
    nickname: userPhone, //昵称
    account: userPhone, //账号
    password //密码
  })
  usermanage
    .save()
    .then(data => {
      response.json({
        code: SUCCESS,
        data: null
      })
      console.log('用户保存成功', data)
      return data
    })
    .then(({ userNo }) => {
      return new vipManage({ userNo }).save()
    })
    .then(data => {
      console.log('用户等级初始化成功', data)
    })
    .catch(err => {
      next([err])
    })
})
// 二维码解码
router.get('/common/qrcode/:amount', (request, response, next) => {
  decodeImage(path.join(__dirname, `../public/imgs/${request.params.amount}.jpg`), (err, image) => {
    if (err) {
      return next(['图片解析失败1' + err])
    }
    let decodeQR = new qrcodeReader()
    decodeQR.callback = function (errorWhenDecodeQR, result) {
      if (errorWhenDecodeQR) {
        return next(['图片解析失败2'])
      }
      if (!result) {
        return next(['图片解析失败3'])
      } else {
        try {
          var img = qr.image(result.result, { size: 10 })
          response.writeHead(200, { 'Content-Type': 'image/png' })
          img.pipe(response)
        } catch (e) {
          response.writeHead(414, { 'Content-Type': 'text/html' })
          response.end('<h1>414 Request-URI Too Large</h1>')
        }
      }
    }
    decodeQR.decode(image.bitmap)
  })
})
// 发评论
/**
 * 传参：
 * @param {string} userNo
 * @param {string} modeNo
 * @param {string} content
 */
router.post('/common/publish-comment', (request, response, next) => {
  if (!request.body.userNo) return next(['未登录', NOLOGIN])
  const params = handData(request.body)
  if (params.modeNo.slice(0, 2) == 'GQ') {
    params.songNo = params.modeNo
  } else if (params.modeNo.slice(0, 2) == 'GS') {
    params.songerNo = params.modeNo
  } else if (params.modeNo.slice(0, 2) == 'GD') {
    params.songlistNo = params.modeNo
  } else {
    return next(['模块编号没传', ERROR])
  }
  delete params.modeNo
  const commentmanage = new commentManage(params)
  commentmanage
    .save()
    .then(() => {
      return response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(err => next(err))
})
// 删评论
/**
 * 传参：
 * @param {string} commentNo
 */
router.delete('/common/comment/:commentNo', (request, response, next) => {
  commentManage
    .deleteOne({ commentNo: request.params.commentNo })
    .then(() => {
      return response.json({
        code: SUCCESS,
        data: null
      })
    })
    .catch(err => next(err))
})
module.exports = router
